package com.tencent.wxcloudrun.controller;

import com.tencent.wxcloudrun.common.InsufficientPrivilegesException;
import com.tencent.wxcloudrun.common.LoginTimeOutException;
import com.tencent.wxcloudrun.config.ErrorResult;
import com.tencent.wxcloudrun.config.SuccessResult;
import com.tencent.wxcloudrun.dto.UserEntity;
import com.tencent.wxcloudrun.service.UserService;
import com.tencent.wxcloudrun.service.WxService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @Resource
    WxService wxService;

    @RequestMapping("/login")
    public SuccessResult userLogin (@RequestBody Map<String, Object> userInfo) {
        try {
            UserEntity user = userService.loginUser(userInfo);
            if (user == null) {
                return SuccessResult.UserNameUndefined();
            }
            if (user.getPassword().equals(userInfo.get("password"))) {
                return SuccessResult.LoginSuccess(user);
            }
            return SuccessResult.PasswordFailed();
        } catch (Exception e) {
            e.printStackTrace();
            return SuccessResult.SystemError(e);
        }
    }

    @RequestMapping("/login_wx")
    public SuccessResult userLoginForWx (@RequestBody Map<String, Object> codeInfo) {
        if (codeInfo.get("code").toString() == null || codeInfo.get("code").toString().length() == 0) {
            return SuccessResult.SystemError("code不能为空");
        }
        if (codeInfo.get("phone").toString() == null || codeInfo.get("phone").toString().length() == 0) {
            return SuccessResult.SystemError("phone不能为空");
        }
        if (codeInfo.get("encryptedData").toString() == null || codeInfo.get("encryptedData").toString().length() == 0) {
            return SuccessResult.SystemError("encryptedData不能为空");
        }
        if (codeInfo.get("iv").toString() == null || codeInfo.get("iv").toString().length() == 0) {
            return SuccessResult.SystemError("iv不能为空");
        }
        // 此处返回 session_key 和 openid
        return wxService.getUserInfo(codeInfo.get("code").toString(), codeInfo.get("encryptedData").toString(), codeInfo.get("iv").toString());
//        JSONObject sessionIdAndOpenId = wxService.getSessionId(codeInfo.get("code").toString());
//        try {
//            JSONObject userInfo = AESCBCUtil.decrypt(codeInfo.get("encryptedData").toString(), sessionIdAndOpenId.get("session_key").toString(), codeInfo.get("iv").toString());
//            if (null != userInfo) {
//                System.out.println("解密成功");
//                Map<String, Object> res = new HashMap<>();
//                res.put("data", userInfo);
//                res.put("total", 0L);
//                return ResultResponse.SelectSuccess(res);
//            }
//            return ResultResponse.SystemError("未解析出用户数据");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return ResultResponse.SystemError("系统出错");
    }

    @RequestMapping("/signIn")
    public SuccessResult userSignIn (@RequestBody Map<String, Object> signInfo) {
        try {
            UserEntity user = new UserEntity();
            user.setUserId(UUID.randomUUID().toString().replace("-", ""));
            user.setUserName(signInfo.get("userName").toString());
            user.setPassword(signInfo.get("password").toString());
            user.setPhone(Long.parseLong(signInfo.get("phone").toString()));
            boolean isSuccess = userService.SignInUser(user);
            if (isSuccess) {
                return SuccessResult.SignInSuccess();
            }
            return SuccessResult.SignInFailed();
        } catch (Exception e) {
            return SuccessResult.SystemError(e);
        }
    }

    @RequestMapping("/updateUser")
    public SuccessResult updateUser (@RequestBody Map<String, Object> userInfo) {
        try {
            boolean isSuccess = userService.UpdateUser(userInfo);
            if (isSuccess) {
                return SuccessResult.UpdateSuccess();
            }
            return SuccessResult.UpdateFailed();
        } catch (Exception e) {
            return SuccessResult.SystemError(e);
        }
    }

    @RequestMapping("/getUser")
    public SuccessResult getUserInfo () {
        throw new LoginTimeOutException();
    }

    @RequestMapping("/test")
    public SuccessResult checkTest () {
        throw new InsufficientPrivilegesException();
    }
}
